// 配置管理模块

use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::fs;
use log::{info, warn};

/// 配置格式枚举
#[derive(Debug, Clone, Copy)]
pub enum ConfigFormat {
    Toml,
    Json,
    Yaml,
}

/// 服务配置
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ServiceConfig {
    pub enabled: bool,
    pub auto_start: bool,
    pub priority: u32,
    pub parameters: HashMap<String, String>,
}

/// 系统配置
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SystemConfig {
    pub boot_services: Vec<String>,
    pub services: HashMap<String, ServiceConfig>,
    pub logging_level: String,
    pub run_example_graphics_app: Option<bool>,
}

impl Default for SystemConfig {
    fn default() -> Self {
        SystemConfig {
            boot_services: vec![
                "memory".to_string(),
                "process".to_string(),
                "filesystem".to_string(),
                "network".to_string(),
            ],
            services: HashMap::new(),
            logging_level: "info".to_string(),
            run_example_graphics_app: Some(false),
        }
    }
}

/// 配置管理器
pub struct ConfigManager {
    config_path: String,
    format: ConfigFormat,
    config: SystemConfig,
}

impl ConfigManager {
    pub fn new(config_path: &str, format: ConfigFormat) -> Self {
        ConfigManager {
            config_path: config_path.to_string(),
            format,
            config: SystemConfig::default(),
        }
    }

    pub fn load(&mut self) -> Result<(), String> {
        if !std::path::Path::new(&self.config_path).exists() {
            warn!("Config file {} not found, using default configuration", self.config_path);
            return Ok(());
        }

        let content = fs::read_to_string(&self.config_path)
            .map_err(|e| format!("Failed to read config file: {}", e))?;

        self.config = match self.format {
            ConfigFormat::Toml => toml::from_str(&content)
                .map_err(|e| format!("Failed to parse TOML config: {}", e))?,
            ConfigFormat::Json => serde_json::from_str(&content)
                .map_err(|e| format!("Failed to parse JSON config: {}", e))?,
            ConfigFormat::Yaml => serde_yaml::from_str(&content)
                .map_err(|e| format!("Failed to parse YAML config: {}", e))?,
        };

        info!("Configuration loaded from {}", self.config_path);
        Ok(())
    }

    pub fn save(&self) -> Result<(), String> {
        let content = match self.format {
            ConfigFormat::Toml => toml::to_string_pretty(&self.config)
                .map_err(|e| format!("Failed to serialize TOML: {}", e))?,
            ConfigFormat::Json => serde_json::to_string_pretty(&self.config)
                .map_err(|e| format!("Failed to serialize JSON: {}", e))?,
            ConfigFormat::Yaml => serde_yaml::to_string(&self.config)
                .map_err(|e| format!("Failed to serialize YAML: {}", e))?,
        };

        fs::write(&self.config_path, content)
            .map_err(|e| format!("Failed to write config file: {}", e))?;

        info!("Configuration saved to {}", self.config_path);
        Ok(())
    }

    pub fn get_config(&self) -> &SystemConfig {
        &self.config
    }

    pub fn get_config_mut(&mut self) -> &mut SystemConfig {
        &mut self.config
    }

    pub fn apply_logging_level(&self) {
        let level = match self.config.logging_level.to_lowercase().as_str() {
            "error" => log::LevelFilter::Error,
            "warn" => log::LevelFilter::Warn,
            "info" => log::LevelFilter::Info,
            "debug" => log::LevelFilter::Debug,
            "trace" => log::LevelFilter::Trace,
            _ => log::LevelFilter::Info,
        };

        env_logger::Builder::new()
            .filter_level(level)
            .init();
    }
}